package com.changgou.filter;

import com.changgou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";

    // 没有登录时跳转到登录页面
    private static final String login_url = "http://localhost:9001/oauth/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 获取response
        ServerHttpResponse response = exchange.getResponse();
        // 如果是登录的请求就放行
        String path = request.getURI().getPath();
        if(path.startsWith("/api/user/login")) {
            // 放行
            Mono<Void> filter = chain.filter(exchange);
            return filter;
        }

        // 判断请求头中是否有令牌信息
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }
        // 判断cookie中是否带有token
        HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
        if(cookie != null) {
            token = cookie.getValue();
        }
        // 如果还是为空则说明没有登录
        if(StringUtils.isEmpty(token)) {
            // 没有令牌直接跳转到登录页面
            response.getHeaders().set("Location", login_url+"?from_url="+request.getURI().toString());
            // 设置方法不允许访问,
            response.setStatusCode(HttpStatus.SEE_OTHER);
            return response.setComplete();
        }
        // 解析令牌数据
        try {
            // Claims claims = JwtUtil.parseJWT(token);
            // 将令牌数据添加到头文件中
            // request.mutate().header(AUTHORIZE_TOKEN, claims.toString());
            request.mutate().header(AUTHORIZE_TOKEN, "Bearer "+token);
        } catch (Exception e) {
            e.printStackTrace();
            // 设置方法不允许访问,返回405
            response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
            return response.setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
